package com.atgion.service.interceptor;

import com.alibaba.fastjson.JSON;
import com.atgion.spzx.model.entity.system.SysUser;
import com.atgion.util.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


//拦截器
public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    // 预处理方法 在拦截器中获取用户信息
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        String UserLogin = redisTemplate.opsForValue().get(token);
        SysUser userInfo = JSON.parseObject(UserLogin, SysUser.class);
        AuthContextUtil.setUserInfo(userInfo); //将用户信息放入上下文
        return true;
    }

    // 后处理

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        AuthContextUtil.removeUserInfo();
    }

}
